package com.bl.student.service.biz.hx.impl;

import com.bl.student.common.ApiResponseCode;
import com.bl.student.common.CommonServiceException;
import com.bl.student.common.template.SysMessageTemplate;
import com.bl.student.common.utils.JSONUtil;
import com.bl.student.dao.model.UserEntity;
import com.bl.student.dao.repository.UserRepository;
import com.bl.student.service.biz.hx.HxAuthService;
import com.bl.student.service.biz.hx.HxMessageService;
import com.bl.student.service.vo.message.HxMessageBodyVo;
import com.bl.student.tp.hx.message.HxMessageApi;
import com.bl.student.tp.hx.message.HxSendMessageRequest;
import com.bl.student.tp.hx.message.HxSendMessageResponse;
import com.google.common.base.Optional;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yujingyi on 2017/8/27.
 */
@Service
@Log4j2
public class HxMessageServiceImpl implements HxMessageService {

    static final private String ADMIN_NAME = "__admin__";
    static final private String TYPE_NAME = "txt";
    static final private String TARGET_TYPE = "users";

    @Autowired
    HxMessageApi hxMessageApi;

    @Autowired
    HxAuthService hxAuthService;

    @Autowired
    UserRepository userRepository;

    @Override
    public void sendMessage(SysMessageTemplate template) {

        List<UserEntity> userList  = userRepository.findAll();

        List<String> accountList = new ArrayList<>();

//        for (UserEntity user : userList) {
//            accountList.add(user.getMobile());
//        }

//        accountList.add("17600853261");
//        accountList.add("15535123007");

        HxMessageBodyVo hxMessageBodyVo = HxMessageBodyVo.builder()
                .content(template.getContent())
                .time(System.currentTimeMillis())
                .build();
        HxSendMessageRequest.Msg msg = HxSendMessageRequest.Msg.builder()
                .msg(JSONUtil.jsonEncode(hxMessageBodyVo))
                .type(TYPE_NAME)
                .build();
        HxSendMessageRequest hxSendMessageRequest = HxSendMessageRequest.builder()
                .msg(msg)
                .target_type(TARGET_TYPE)
                .from(ADMIN_NAME)
                .target(accountList)
                .build();

//        Optional<HxSendMessageResponse> hxSendMessageResponseOptional = hxMessageApi.sendMessage(hxSendMessageRequest, hxAuthService.getAndSetAccessToken());
//        if (hxSendMessageResponseOptional.isPresent()) {
//            HxSendMessageResponse hxSendMessageResponse = hxSendMessageResponseOptional.get();
//        } else {
//            throw new CommonServiceException(ApiResponseCode.HX_REQUEST_FAILED.getCode(), ApiResponseCode.HX_REQUEST_FAILED.getMsg());
//
//        }

    }
}
